#pragma once

#include "Log.hpp"
#include "Err.hpp"

#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

class Sock
{
    const static int default_sock = -1;
    const static int default_backlog = 32;
public:
    Sock()
        :sock(default_sock)
    {}

    // 创建套接字
    void Socket()
    {
        sock = socket(AF_INET, SOCK_STREAM, 0);
        if(sock == -1)
        {
            logMessage(Fatal, "Creater Socket Fail! [%d]->%s", errno, strerror(errno));
            exit(SOCKET_ERR);
        }
        logMessage(Debug, "Creater Socket Success");
    }

    // 绑定IP与端口号
    void Bind(const uint16_t& port)
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));

        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;

        if(bind(sock, (struct sockaddr*)&local, sizeof(local)) == -1)
        {
            logMessage(Fatal, "Bind Socket Fail! [%d]->%s", errno, strerror(errno));
            exit(BIND_ERR);
        }
        logMessage(Debug, "Bind Socket Success");
    }

    // 进入监听状态
    void Listen()
    {
        if(listen(sock, default_backlog) == -1)
        {
            logMessage(Fatal, "Listen Socket Fail! [%d]->%s", errno, strerror(errno));
            exit(LISTEN_ERR);
        }
    }

    // 尝试处理连接请求
    int Accept(std::string* ip, uint16_t* port)
    {
        struct sockaddr_in client;
        socklen_t len = sizeof(client);

        int retSock = accept(sock, (struct sockaddr*)&client, &len);
        if(retSock < 0)
            logMessage(Warning, "Accept Fail! [%d]->%s", errno, strerror(errno));
        else
        {
            *ip = inet_ntoa(client.sin_addr);
            *port = ntohs(client.sin_port);
            logMessage(Debug, "Accept [%d -> %s:%d] Success", retSock, ip->c_str(), *port);
        }

        return retSock;
    }

    // 尝试进行连接
    int Connect(const std::string& ip, const uint16_t& port)
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));

        server.sin_family = AF_INET;
        server.sin_port = htons(port);
        server.sin_addr.s_addr = inet_addr(ip.c_str());

        return connect(sock, (struct sockaddr*)&server, sizeof(server));
    }

    // 获取sock
    int GetSock()
    {
        return sock;
    }

    // 关闭sock
    void Close()
    {
        if(sock != default_sock)
            close(sock);
        logMessage(Debug, "Close Sock Success");
    }

    ~Sock()
    {}
private:
    int sock; // 既可以是监听套接字，也可以是连接成功后返回的套接字
};
